const app = getApp()

Page({
  data: {
    orderId: '',
    amount: 0,
    countdown: 900, // 15分钟倒计时
    countdownText: '15:00',
    timer: null,
    
    // 订单信息
    orderInfo: {
      storeName: '',
      orderType: '',
      items: [],
      totalAmount: 0,
      createTime: ''
    },
    
    // 支付方式
    paymentMethods: [
      {
        id: 'wechat',
        name: '微信支付',
        icon: '/images/payment/wechat.png',
        desc: '推荐使用微信支付',
        selected: true,
        available: true
      },
      {
        id: 'alipay',
        name: '支付宝',
        icon: '/images/payment/alipay.png',
        desc: '支持花呗分期',
        selected: false,
        available: true
      },
      {
        id: 'balance',
        name: '余额支付',
        icon: '/images/payment/balance.png',
        desc: '余额: ¥128.50',
        selected: false,
        available: false // 余额不足
      }
    ],
    
    // 支付状态
    paymentStatus: 'pending', // pending: 待支付, processing: 支付中, success: 支付成功, failed: 支付失败
    paying: false,
    
    // 优惠信息
    discountInfo: {
      couponDiscount: 0,
      platformDiscount: 0,
      totalDiscount: 0
    }
  },

  onLoad(options) {
    const { orderId, amount } = options
    
    this.setData({
      orderId: orderId || '',
      amount: parseFloat(amount) || 0
    })
    
    this.initPage()
  },

  onShow() {
    // 检查支付状态
    this.checkPaymentStatus()
  },

  onHide() {
    this.clearTimer()
  },

  onUnload() {
    this.clearTimer()
  },

  // 初始化页面
  async initPage() {
    wx.setNavigationBarTitle({
      title: '收银台'
    })
    
    await this.loadOrderInfo()
    this.startCountdown()
  },

  // 加载订单信息
  async loadOrderInfo() {
    try {
      // 模拟订单数据
      const mockOrderInfo = {
        orderId: this.data.orderId,
        storeName: '麦当劳(王府井店)',
        orderType: 'delivery',
        items: [
          { name: '巨无霸', quantity: 2, price: 25.5 },
          { name: '薯条(大)', quantity: 1, price: 12.0 },
          { name: '可乐(中)', quantity: 2, price: 8.5 }
        ],
        totalAmount: this.data.amount,
        createTime: new Date().toLocaleString(),
        deliveryAddress: '北京市朝阳区三里屯SOHO 3号楼1001室'
      }
      
      // 模拟优惠信息
      const mockDiscountInfo = {
        couponDiscount: 10,
        platformDiscount: 5,
        totalDiscount: 15
      }
      
      this.setData({
        orderInfo: mockOrderInfo,
        discountInfo: mockDiscountInfo
      })
      
    } catch (error) {
      console.error('加载订单信息失败:', error)
      wx.showToast({
        title: '加载订单信息失败',
        icon: 'none'
      })
    }
  },

  // 开始倒计时
  startCountdown() {
    this.clearTimer()
    
    this.data.timer = setInterval(() => {
      let countdown = this.data.countdown - 1
      
      if (countdown <= 0) {
        this.clearTimer()
        this.handlePaymentTimeout()
        return
      }
      
      const minutes = Math.floor(countdown / 60)
      const seconds = countdown % 60
      const countdownText = `${minutes.toString().padStart(2, '0')}:${seconds.toString().padStart(2, '0')}`
      
      this.setData({
        countdown,
        countdownText
      })
    }, 1000)
  },

  // 清除定时器
  clearTimer() {
    if (this.data.timer) {
      clearInterval(this.data.timer)
      this.setData({ timer: null })
    }
  },

  // 处理支付超时
  handlePaymentTimeout() {
    wx.showModal({
      title: '支付超时',
      content: '订单支付已超时，请重新下单',
      showCancel: false,
      success: () => {
        wx.navigateBack()
      }
    })
  },

  // 选择支付方式
  selectPaymentMethod(e) {
    const methodId = e.currentTarget.dataset.id
    const method = this.data.paymentMethods.find(m => m.id === methodId)
    
    if (!method.available) {
      wx.showToast({
        title: method.id === 'balance' ? '余额不足' : '支付方式不可用',
        icon: 'none'
      })
      return
    }
    
    const paymentMethods = this.data.paymentMethods.map(m => ({
      ...m,
      selected: m.id === methodId
    }))
    
    this.setData({ paymentMethods })
  },

  // 立即支付
  async payNow() {
    if (this.data.paying) return
    
    // 检查支付方式
    const selectedMethod = this.data.paymentMethods.find(m => m.selected)
    if (!selectedMethod) {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none'
      })
      return
    }
    
    if (!selectedMethod.available) {
      wx.showToast({
        title: '当前支付方式不可用',
        icon: 'none'
      })
      return
    }
    if (!selectedMethod) {
      wx.showToast({
        title: '请选择支付方式',
        icon: 'none'
      })
      return
    }
    
    this.setData({ paying: true, paymentStatus: 'processing' })
    
    try {
      await this.processPayment(selectedMethod)
    } catch (error) {
      console.error('支付失败:', error)
      this.setData({ 
        paying: false, 
        paymentStatus: 'failed' 
      })
      
      wx.showModal({
        title: '支付失败',
        content: '支付过程中出现错误，请重试',
        showCancel: true,
        cancelText: '取消订单',
        confirmText: '重新支付',
        success: (res) => {
          if (res.cancel) {
            this.cancelOrder()
          } else {
            this.setData({ paymentStatus: 'pending' })
          }
        }
      })
    }
  },

  // 处理支付
  async processPayment(paymentMethod) {
    switch (paymentMethod.id) {
      case 'wechat':
        await this.wechatPay()
        break
      case 'alipay':
        await this.alipay()
        break
      case 'balance':
        await this.balancePay()
        break
      default:
        throw new Error('不支持的支付方式')
    }
  },

  // 微信支付
  async wechatPay() {
    try {
      // 模拟调用支付API
      const paymentParams = await this.mockGetPaymentParams()
      
      // 调用微信支付
      await new Promise((resolve, reject) => {
        wx.requestPayment({
          ...paymentParams,
          success: resolve,
          fail: reject
        })
      })
      
      this.handlePaymentSuccess()
      
    } catch (error) {
      if (error.errMsg && error.errMsg.includes('cancel')) {
        // 用户取消支付
        this.setData({ 
          paying: false, 
          paymentStatus: 'pending' 
        })
      } else {
        throw error
      }
    }
  },

  // 支付宝支付
  async alipay() {
    // 模拟支付宝支付
    await this.mockPayment()
    this.handlePaymentSuccess()
  },

  // 余额支付
  async balancePay() {
    // 模拟余额支付
    await this.mockPayment()
    this.handlePaymentSuccess()
  },

  // 模拟获取支付参数
  mockGetPaymentParams() {
    return new Promise((resolve) => {
      setTimeout(() => {
        resolve({
          timeStamp: Date.now().toString(),
          nonceStr: 'mock_nonce_str',
          package: 'prepay_id=mock_prepay_id',
          signType: 'MD5',
          paySign: 'mock_pay_sign'
        })
      }, 1000)
    })
  },

  // 模拟支付过程
  mockPayment() {
    return new Promise((resolve, reject) => {
      setTimeout(() => {
        // 90%成功率
        if (Math.random() > 0.1) {
          resolve()
        } else {
          reject(new Error('支付失败'))
        }
      }, 2000)
    })
  },

  // 处理支付成功
  handlePaymentSuccess() {
    this.clearTimer()
    this.setData({ 
      paying: false, 
      paymentStatus: 'success' 
    })
    
    wx.showToast({
      title: '支付成功',
      icon: 'success',
      duration: 2000
    })
    
    setTimeout(() => {
      wx.redirectTo({
        url: `/pages/payment-result/payment-result?orderId=${this.data.orderId}&status=success`
      })
    }, 2000)
  },

  // 检查支付状态
  async checkPaymentStatus() {
    try {
      // 模拟检查支付状态
      // 实际应用中这里会调用后端API
      console.log('检查支付状态:', this.data.orderId)
    } catch (error) {
      console.error('检查支付状态失败:', error)
    }
  },

  // 取消订单
  cancelOrder() {
    wx.showModal({
      title: '确认取消',
      content: '确定要取消这个订单吗？',
      success: (res) => {
        if (res.confirm) {
          this.clearTimer()
          
          // 调用取消订单API
          this.mockCancelOrder().then(() => {
            wx.showToast({
              title: '订单已取消',
              icon: 'success'
            })
            
            setTimeout(() => {
              wx.navigateBack()
            }, 1500)
          }).catch((error) => {
            console.error('取消订单失败:', error)
            wx.showToast({
              title: '取消失败，请重试',
              icon: 'none'
            })
          })
        }
      }
    })
  },

  // 模拟取消订单
  mockCancelOrder() {
    return new Promise((resolve) => {
      setTimeout(resolve, 1000)
    })
  },

  // 查看订单详情
  viewOrderDetail() {
    wx.navigateTo({
      url: `/pages/order-detail/order-detail?id=${this.data.orderId}`
    })
  },

  // 联系客服
  contactService() {
    wx.showModal({
      title: '联系客服',
      content: '客服电话：400-123-4567\n工作时间：9:00-21:00',
      showCancel: false
    })
  },

  // 分享订单
  onShareAppMessage() {
    return {
      title: `我在${this.data.orderInfo.storeName}点了外卖`,
      path: `/pages/store-detail/store-detail?id=${this.data.orderInfo.storeId}`,
      imageUrl: '/images/share-order.png'
    }
  }
}) 